package de.hijacksoft.isledesktopsync;

import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import de.hijacksoft.isledesktopsync.adapter.DBAdapter;
import de.hijacksoft.isledesktopsync.adapter.StatusListener;
import de.hijacksoft.isledesktopsync.adapter.USBDataAdapter;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import static de.hijacksoft.isledesktopsync.Globals.*;

public class MainWindow extends javax.swing.JFrame implements StatusListener {
    
    // Strings
    private static final String STRING_SUBTITLE = "subtitle";
    private static final String STRING_TITLE = "title";
    private static final String STRING_CONNECTED = "toast_connected";
    private static final String STRING_DISCONNECTED = "toast_disconnected";
    private static final String STRING_RESTORE = "btn_restore";
    private static final String STRING_BACKUP = "btn_backup";
    private static final String STRING_INSPECT = "btn_inspect";
    private static final String STRING_ADBSELECT = "adbselect";        
    private static final String STRING_WARNING = "warning";
    private static final String STRING_RESTORE_WARNING = "restore_warning";
    private static final String STRING_WRITTEN = "toast_written";
    private static final String STRING_READ = "toast_read";
    private static final String STRING_OPENDB = "opendb";
    private static final String STRING_SAVE= "save";
    
    private SettingsManager settings;
    private DBAdapter dbAdapter = new DBAdapter();
    private USBDataAdapter usbAdapter = new USBDataAdapter();
    private LocalizationManager localization;

    public MainWindow() {
        initComponents();
        handlePreferences();
        initLocalization();
        
        // get the adb path if none has been entered
        if(settings.getString(SETTING_ADBPATH) == null)
        {
            JFileChooser chooser = new JFileChooser();
            chooser.setCurrentDirectory(new java.io.File("."));
            chooser.setDialogTitle(getString(STRING_ADBSELECT));
            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            chooser.setAcceptAllFileFilterUsed(false);
            if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
                settings.saveString(SETTING_ADBPATH, chooser.getSelectedFile().toString());
            }
                
        }
        
        usbAdapter.addStatusListener(this);
        usbAdapter.open();
    }
    
    private void initLocalization() {
        localization = LocalizationManager.getInstance();
        
        btnSync.setText(getString(STRING_BACKUP));
        btnRestore.setText(getString(STRING_RESTORE));
        btnEdit.setText(getString(STRING_INSPECT));
        prodNameSub.setText(getString(STRING_SUBTITLE));
        this.setTitle(getString(STRING_TITLE) + " " + getString(STRING_SUBTITLE));
        
    }
    
    public String getString(String key){
        try {
            return localization.getString(key);
        } catch (Exception ex) {
            System.out.println(ex.toString());
        }
        return null;
    }
    
    private void handlePreferences() {
        settings = SettingsManager.getInstance();

        try {
            setLocation(settings.getInt(SETTING_WINDOWX), settings.getInt(SETTING_WINDOWY));
        } catch (Exception e) {
            System.err.println("some settings could not be loaded...");
            // e.printStackTrace();
        }

    }
    
    @Override
    public void onStatusChange(int status, USBDataAdapter usbAdapter) {

        System.out.println("status changed to " + status);
        
        switch(status){
            case USBDataAdapter.STATUS_RECIEVE_REQUEST: {
                int n = JOptionPane.showConfirmDialog(this, getString(STRING_RESTORE_WARNING), getString(STRING_WARNING), JOptionPane.OK_CANCEL_OPTION);
                switch(n){
                    case JOptionPane.OK_OPTION: 
                        File dbFile = showOpenDialog();
                        if(dbFile != null) {
                            btnSync.setEnabled(false);
                            btnRestore.setEnabled(false);
                            usbAdapter.writeDatabase(dbAdapter.readDBFromFile(dbFile));
                        }
                        break;
                    default: ;
                }
                break;
            }
            case USBDataAdapter.STATUS_CONNECTING: {
                btnSync.setEnabled(false);
                btnRestore.setEnabled(false);
                break;
            }
            case USBDataAdapter.STATUS_CONNECTED: {
                btnSync.setEnabled(true);
                btnRestore.setEnabled(true);
                Toast.makeText(getString(STRING_CONNECTED), 2000).show();
                break;
            } 
            case USBDataAdapter.STATUS_READ_FINISHED: ; {
                long time = System.currentTimeMillis();
                dbAdapter.storeDB(usbAdapter.getDatabse(), "./database/" + time + ".db");
                btnSync.setEnabled(true);
                btnRestore.setEnabled(true);
                Toast.makeText(getString(STRING_READ), 2000).show();
                settings.saveString(Globals.SETTING_LASTDB, "./database/" + time + ".db");
                break;
            }
            case USBDataAdapter.STATUS_WRITE_FINISHED: ; {
                dbAdapter.storeDB(usbAdapter.getDatabse(), "./database/" + System.currentTimeMillis() + ".db");
                btnSync.setEnabled(true);
                btnRestore.setEnabled(true);
                Toast.makeText(getString(STRING_WRITTEN), 2000).show();
                break;
            }
            case USBDataAdapter.STATUS_DISCONNECTED: {
                btnSync.setEnabled(false);
                btnRestore.setEnabled(false);
                Toast.makeText(getString(STRING_DISCONNECTED), 2000).show();
                break;
            }
        }
    }

/** This method is called from within the constructor to
 * initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is
 * always regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        windowFrame = new javax.swing.JFrame();
        windowBackground = new javax.swing.JPanel(){
            public void paintComponent(Graphics g)
            {
                Image img = new ImageIcon("res/background.png").getImage();
                Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
                setPreferredSize(size);
                setMinimumSize(size);
                setMaximumSize(size);
                setSize(size);
                setLayout(null);
                g.drawImage(img, 0, 0, null);
            }
        };
        btnSync = new javax.swing.JButton();
        btnEdit = new javax.swing.JButton();
        prodName = new javax.swing.JLabel();
        prodNameSub = new javax.swing.JLabel();
        btnRestore = new javax.swing.JButton();
        toastPanel = new Toast(windowBackground);

        windowFrame.setResizable(false);
        windowFrame.addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                windowFrameWindowClosing(evt);
            }
        });

        org.jdesktop.layout.GroupLayout windowFrameLayout = new org.jdesktop.layout.GroupLayout(windowFrame.getContentPane());
        windowFrame.getContentPane().setLayout(windowFrameLayout);
        windowFrameLayout.setHorizontalGroup(
            windowFrameLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 400, Short.MAX_VALUE)
        );
        windowFrameLayout.setVerticalGroup(
            windowFrameLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 300, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("ISLE Desktop Sync");
        setForeground(java.awt.Color.white);
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        windowBackground.setPreferredSize(new java.awt.Dimension(768, 512));

        btnSync.setFont(new java.awt.Font("Droid Sans", 0, 18));
        btnSync.setText("Backup");
        btnSync.setEnabled(false);
        btnSync.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSyncActionPerformed(evt);
            }
        });

        btnEdit.setFont(new java.awt.Font("Droid Sans", 0, 18));
        btnEdit.setText("Inspect");
        btnEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditActionPerformed(evt);
            }
        });

        prodName.setFont(new java.awt.Font("Droid Sans", 0, 200));
        prodName.setText("ISLE");

        prodNameSub.setFont(new java.awt.Font("Lucida Grande", 0, 24)); // NOI18N
        prodNameSub.setText("Desktop-Synchronization");

        btnRestore.setFont(new java.awt.Font("Droid Sans", 0, 18));
        btnRestore.setText("Restore");
        btnRestore.setEnabled(false);
        btnRestore.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRestoreActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout toastPanelLayout = new org.jdesktop.layout.GroupLayout(toastPanel);
        toastPanel.setLayout(toastPanelLayout);
        toastPanelLayout.setHorizontalGroup(
            toastPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 399, Short.MAX_VALUE)
        );
        toastPanelLayout.setVerticalGroup(
            toastPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 111, Short.MAX_VALUE)
        );

        org.jdesktop.layout.GroupLayout windowBackgroundLayout = new org.jdesktop.layout.GroupLayout(windowBackground);
        windowBackground.setLayout(windowBackgroundLayout);
        windowBackgroundLayout.setHorizontalGroup(
            windowBackgroundLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(windowBackgroundLayout.createSequentialGroup()
                .addContainerGap()
                .add(windowBackgroundLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, windowBackgroundLayout.createSequentialGroup()
                        .add(21, 21, 21)
                        .add(btnSync, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 206, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 32, Short.MAX_VALUE)
                        .add(btnRestore, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 206, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(37, 37, 37)
                        .add(btnEdit, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 206, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(windowBackgroundLayout.createSequentialGroup()
                        .add(309, 309, 309)
                        .add(windowBackgroundLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, toastPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(windowBackgroundLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                                .add(prodNameSub)
                                .add(prodName)))))
                .addContainerGap())
        );
        windowBackgroundLayout.setVerticalGroup(
            windowBackgroundLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(windowBackgroundLayout.createSequentialGroup()
                .add(30, 30, 30)
                .add(prodName, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 163, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(prodNameSub, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 46, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(toastPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(windowBackgroundLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(btnEdit, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 77, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(btnRestore, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 77, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(btnSync, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 77, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(windowBackground, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 728, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(windowBackground, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 469, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    public File showSaveDialog(){
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new java.io.File("."));
        chooser.setDialogTitle(getString(STRING_SAVE));
        chooser.setAcceptAllFileFilterUsed(false);
        if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
            return chooser.getSelectedFile();
        }
        else return null;
    }
    
    public File showOpenDialog(){
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new java.io.File("."));
        chooser.setDialogTitle(getString(STRING_OPENDB));
        chooser.setAcceptAllFileFilterUsed(false);
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            return chooser.getSelectedFile();
        }
        else return null;
    }

    private void btnSyncActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSyncActionPerformed
        
        btnSync.setEnabled(false);
        usbAdapter.readDatabase();
        
    }//GEN-LAST:event_btnSyncActionPerformed
    private void windowFrameWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_windowFrameWindowClosing

    }//GEN-LAST:event_windowFrameWindowClosing

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        
        settings.saveInt(SETTING_WINDOWX, getX());
        settings.saveInt(SETTING_WINDOWY, getY());
        usbAdapter.close();
        
    }//GEN-LAST:event_formWindowClosing

    private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
        EditWindow ew = EditWindow.getInstance();
        if(!ew.isVisible()){
            ew.setLocation(this.getLocation());
            ew.setVisible(true);
        }
    }//GEN-LAST:event_btnEditActionPerformed

    private void btnRestoreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRestoreActionPerformed
        int n = JOptionPane.showConfirmDialog(this, getString(STRING_RESTORE_WARNING), getString(STRING_WARNING), JOptionPane.OK_CANCEL_OPTION);
        switch(n){
            case JOptionPane.OK_OPTION: 
                usbAdapter.writeDatabase(dbAdapter.readDBFromFile(showOpenDialog()));
                break;
            default: ;
        }                                     
    }//GEN-LAST:event_btnRestoreActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
                new MainWindow().setVisible(true);
            }
        });
        
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    public javax.swing.JButton btnEdit;
    public javax.swing.JButton btnRestore;
    public javax.swing.JButton btnSync;
    public javax.swing.JLabel prodName;
    public javax.swing.JLabel prodNameSub;
    public javax.swing.JPanel toastPanel;
    public javax.swing.JPanel windowBackground;
    public javax.swing.JFrame windowFrame;
    // End of variables declaration//GEN-END:variables
    
        
}